package com.block.datapush.form.item;

import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.service.LogFactory;
import com.block.datapush.form.enums.PushResultEnum;
import com.block.datapush.form.service.IFormPushHandle;
import com.block.datapush.model.dto.FormPushResultDTO;
import com.block.datapush.form.item.util.DianDaiUtil;
import com.block.db.entity.FormInfo;
import com.block.db.entity.FormInfoHis;
import com.block.db.entity.MemberExtInfo;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 点贷
 *
 */
@Service
public class DianDaiPushHandleService implements IFormPushHandle {

    private static final Logger log = LogFactory.getPushLog();

    /**
     * /api/Infos/userExist
     * @param formInfo
     * @param memberExtInfo
     * @return
     */
    @Override
    public boolean queryMatchResult(FormInfo formInfo, MemberExtInfo memberExtInfo) throws Exception {

            String queryUrl = formInfo.getQueryUrl();
            String mobileMd5 = SecureUtil.md5(memberExtInfo.getMobile()).toLowerCase();

            Long timestamp = System.currentTimeMillis();

            String sign = this.getSignResult(formInfo.getApiKey(), timestamp, formInfo.getApiSecret());
            String content = this.encryptBizParam(mobileMd5, formInfo.getApiSecret());

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("channel", formInfo.getApiKey());
            paramMap.put("timestamp", timestamp);
            paramMap.put("sign", sign);
            paramMap.put("content", content);

            log.info("【点贷】撞库开始【queryUrl】{}【bizParam】{}【paramMap】{}",
                    queryUrl, JSON.toJSONString(mobileMd5), JSON.toJSONString(paramMap));
            String result = HttpUtil.createPost(queryUrl)
                    .header("Content-Type", "application/json")
                    .body(JSON.toJSONString(paramMap))
                    .execute().body();
            log.info("【点贷】撞库结束【result】{}", result);

            JSONObject resultObject = JSON.parseObject(result);
            Integer status = resultObject.getInteger("status");
            String info = resultObject.getString("info");
            JSONObject data = resultObject.getJSONObject("data");

            if (StrUtil.equals("200", String.valueOf(status))){
                    return true;
            }
            return false;
    }

    /**
     * /api/Infos/receive
     * @param formInfo
     * @param memberExtInfo
     * @param orderNo
     * @param jsonObject
     * @return
     */
    @Override
    public FormPushResultDTO pushMemberInfo(FormInfo formInfo, MemberExtInfo memberExtInfo, String orderNo, JSONObject jsonObject) throws Exception {

        FormPushResultDTO pushResultDTO = new FormPushResultDTO();
        pushResultDTO.setOrderNo(orderNo);

            String queryUrl = formInfo.getRequestUrl();

            Map<String, Object> bizParamMap = new HashMap<>();

            bizParamMap.put("apply_name", memberExtInfo.getUsername());
            bizParamMap.put("id_card", memberExtInfo.getIdCard());
//            bizParamMap.put("phone", orderNo);//
            bizParamMap.put("phone", memberExtInfo.getMobile());//
            bizParamMap.put("phone_md5", SecureUtil.md5(memberExtInfo.getMobile()).toLowerCase());
            bizParamMap.put("age", memberExtInfo.getAge());
            bizParamMap.put("sex", memberExtInfo.getSex()==1?1300:1301);
            bizParamMap.put("province", memberExtInfo.getCityCode());

            bizParamMap.put("loan", DianDaiUtil.getLoanAmount(memberExtInfo.getLoanAmount()));// 额度

            bizParamMap.put("has_social", StrUtil.equals(BaseTypeInfoEnum.SocialInsurance.si001.getValue(), memberExtInfo.getSocialInsurance())?400:401);// 社保
            bizParamMap.put("has_fund", StrUtil.equals(BaseTypeInfoEnum.Gjj.gjj001.getValue(), memberExtInfo.getGjj())?300:301);// 公积金
            bizParamMap.put("life_insurance", StrUtil.equals(BaseTypeInfoEnum.Insurance.in001.getValue(), memberExtInfo.getInsurance())?500:501);// 保险
            bizParamMap.put("house_property", StrUtil.equals(BaseTypeInfoEnum.House.hu001.getValue(), memberExtInfo.getHouse())?100:101);// 房产
            bizParamMap.put("car_property", StrUtil.equals(BaseTypeInfoEnum.Car.car001.getValue(), memberExtInfo.getCar())?200:201);// 车产
            bizParamMap.put("zhima_credit", DianDaiUtil.getZhiMa(memberExtInfo.getZhimaScore()));// 芝麻分
            bizParamMap.put("credit_card", 900);// 信用卡额度
            bizParamMap.put("baitiao", 801);// 白条
            bizParamMap.put("huabei", 701);// 花呗
            bizParamMap.put("business_owner", StrUtil.equals(BaseTypeInfoEnum.EnterpriseOwner.eo001.getValue(), memberExtInfo.getEnterpriseOwner())?600:601);// 学历

            bizParamMap.put("credit_history", 1001);// 信用逾期情况

            Long timestamp = System.currentTimeMillis();

            String sign = this.getSignResult(formInfo.getApiKey(), timestamp, formInfo.getApiSecret());
            String bizParam = this.encryptBizParam(JSON.toJSONString(bizParamMap), formInfo.getApiSecret());

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("channel", formInfo.getApiKey());
            paramMap.put("timestamp", timestamp);
            paramMap.put("sign", sign);
            paramMap.put("content", bizParam);
            paramMap.put("orderNo", orderNo);

            log.info("【点贷】导单开始【queryUrl】{}【bizParam】{}【paramMap】{}", queryUrl, JSON.toJSONString(bizParamMap), JSON.toJSONString(paramMap));
            String result = HttpUtil.createPost(queryUrl)
                    .header("Content-Type", "application/json")
                    .body(JSON.toJSONString(paramMap))
                    .execute().body();
            log.info("【点贷】导单结束【result】{}", result);

            JSONObject resultObject = JSON.parseObject(result);
            Integer status = resultObject.getInteger("status");
            String msg = resultObject.getString("msg");
            JSONObject data = resultObject.getJSONObject("data");

            pushResultDTO.setResult(result);
            pushResultDTO.setCode(String.valueOf(status));
            pushResultDTO.setMessage(UnicodeUtil.toString(msg));
            pushResultDTO.setParamContent(JSON.toJSONString(bizParamMap));

            if (ObjectUtil.equal(status, Integer.valueOf(200))){
                String orderSn = data.getString("order_sn");
                pushResultDTO.setOutOrderNo(orderSn);
                pushResultDTO.setPushResult(PushResultEnum.SUCCESS.getType());
                pushResultDTO.setSuccess(true);// 不接算
            }else{
                pushResultDTO.setPushResult(PushResultEnum.FAILED.getType());
                pushResultDTO.setSuccess(false);
            }
            return pushResultDTO;

    }

    /**
     * 获取签名数据
     * @param apiKey
     * @param timestamp
     * @param apiSecret
     * @return
     */
    private String getSignResult(String apiKey, Long timestamp, String apiSecret) {
        String signStr = StrUtil.format("{}{}{}", apiKey, timestamp, apiSecret);
        return SecureUtil.md5(signStr).toLowerCase();
    }


    /**
     *
     * @param content
     * @param key
     * @return
     */
    public String encryptBizParam(String content, String key) throws Exception{
        byte[] originalContent = content.getBytes(StandardCharsets.UTF_8);
        String keys = key.substring(0,16);
        byte[] encryptKey = keys.getBytes();

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");;
        SecretKeySpec skeySpec = new SecretKeySpec(encryptKey, "AES");
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(originalContent);
        return Base64.encodeBase64String(encrypted);

    }

    @Override
    public void afterPushHandle(FormInfoHis formInfoHis) {

    }

}
